<?php
/**
 * Created by PhpStorm.
 * User: 张鹏
 * Date: 2017-02-27
 * Time: 下午 2:38
 *  Versions;1.01
description:
 * 2017-05-06 10:10 新增方法 getInfoByIdUserId($user_id) 获取用户会员信息 通过user_id
 */

namespace app\common\model;


use think\Db;

class Member
{
    private $userId;
    private $config;
    private $auth;
    private $prefix;
    public function __construct()
    {
        $this->auth = model('Admin')->is('client')['state'];
        $this->config = getConfig('member');
        $this->prefix = config('database.prefix');
        //获取当前user_id
        if (is_null($this->userId)) {
            $userId = $this->userId = model('User')->getUserId();
        } else {
            $userId = $this->userId;
        }
        if (!$userId) {
            return;
        }
    }
    //检查该user_id在该demand下的折扣
    //$demand:类型如:book,cafe
    //$user_id:用户id
    function getDiscountByUserId($demand, $user_id) {
        //$user = new User();
       // $user_id = $user->exist(['tel'=>$tel])['data']['user_id'];
        //取出会员卡配置
        $config = $this->config[0];
        foreach ($config as $k => $v) {
            //配置文件里最大梯度的会员卡
            $class_max[] = $v['id'];
        }
        $class_max_select = implode(',', $class_max);
        //查询该用户已有会员卡
        $userinfo = Db::name('user_member')
            ->where("user_id= '$user_id' and state = 1 and class in($class_max_select)")
            ->order('class desc')
            ->select();
        $discount = 100;
        $info = [];
        if (!empty($userinfo)){
            foreach ($userinfo as $k=>$v){
                $c = null;
                foreach ($config as $key => $config_demand){
                    if( $config_demand['id'] == $userinfo[$k]['class']){
                        $c = $config_demand;
                        $c['demand'] = $key;
                    }
                }
                if($c){
                    if(isset($c['discount'][$demand])&&$discount > $c['discount'][$demand]){
                        $discount = $c['discount'][$demand];
                        $info['discount'] = $discount/100;
                        $info['intro'] = $c['intro'];
                        $info['demand'] = $c['demand'];
                    }
                }
            }
        }
        if(!$info){
            return [
                'state' => 0,
                'errormsg' => 'not find discount'
            ];
        }
        if(isset($info['discount'])&&!$info['discount']){
            return [
                'state' => 0,
                'errormsg' => 'not find discount'
            ];
        }
        return [
            'state' => 1,
            'info' => $info
        ];
    }
    //根据user_id 获取会员信息
    function getInfoByIdUserId($user_id){
        if(!$user_id){
            return ['state'=>0,'errormsg'=>'未找到用户','errorcode'=>'member201'];
        }
        $userinfo = Db::name('user_member')
            ->field('class')
            ->where("user_id= '$user_id' and state = 1")
            ->order('class desc')
            ->select();
        if(!$userinfo){
            return ['state'=>0,'errormsg'=>"未找到用户",'errorcode'=>'member202'];
        }
        $config = $this->config[0];
        $member = [];
        foreach ($userinfo as $key=>$value){
            foreach ($config as $k=>$v){
                if($v['id'] == $value['class']){
                    $userinfo[$key]['demand'] = $k;
                    $userinfo[$key]['intro'] = $v['intro'];
                    $userinfo[$key]['group'] = $v['group'];
                }
            }
        }
        foreach ($userinfo as $k=>$v){
            $tmp[$v['group']][] = $v;
        }
        $i = 0;
        foreach ($tmp as $k=>$v){
         $member[$i]['key'] =$v[0]['demand'];
         $member[$i]['intro'] =$v[0]['intro'];
         $i++;
         //['key'=>$v[0]['demand'],'intro'=>$v[0]['intro']];
        }
        return ['state'=>1,'data'=>$member];
    }
    //add_recharge_once 管理员生成会员(一次性消费)
    public function addRechargeOnce($tel){
        if (!$this->auth){
            return [
                'state' => 0,
                'errormsg' => '暂无权限'
            ];
        }
        if(!$tel){
            return [
                'state' => 0,
                'errormsg' => '请传入电话号码'
            ];
        }
        //根据tel找到用户id
        $user = model('user')->exist(['state'=>1,'tel'=>$tel]);
        if (!$user['state']){
            return [
                'not find user'
            ];
        }
        $user_id = $user['data']['user_id'];
        //获取消费记录
        $prefix = config('database.prefix');
        $pay_info = Db::table($prefix.'pay')
            ->alias('a')
            ->join($prefix.'order b','a.order_id = b.order_id')
            ->where('b.user_id',$user_id)
            ->where('b.class','0')
            ->select();
        //获取配置文件
        $total_fee = 0;
        $class = [];
        if (!empty($pay_info)){
            $total_fee = $pay_info[0]['total_fee'];
        }
        $config = $this->config[0];
        foreach ($config as $key => $value){
            if ($total_fee>=$value['request']['recharge']){
                $class[] = $value['id'];
            }
            $class_max[] = $value['id'];
        }
        $class_max_select = implode(',',$class_max);
        //判断是否达到最低会员要求
        if (empty($class)){
            return [
                'state'=> 0,
                'errormsg' => '未达到最低会员要求'
            ];
        }
        //查询该用户所有会员卡
        $member = Db::name('user_member')
            ->where("user_id = $user_id and class in($class_max_select) and state=1")
            ->order('class desc')
            ->select();
        if (!$member){
            foreach ($class as $k=>$v){
                $data['class']=$class[0];
            }
        }else{
            foreach ($member as $k => $v) {
                if (!(time() - $v['create_time']) / 86400 > $v['temporality'] || !$v['temporality']) {
                    $user_info[] = $v;
                }
            }
            //如果可生成的会员卡类型高于已有会员卡类型，则提示生成对应梯度会员卡
            if (isset($class[0]) && $class[0]>$member[0]){
                $data['class'] = $class[0];
            }else{
                if($class_max[0]=$member[0]){
                    return [
                        'state'=> 0,
                        'errormsg' => '已是最高会员'
                    ];
                }
                return [
                    'state' => 0,
                    'errormsg' => $member[0]['class']+1
                ];
            }
        }
        //会员卡数量限制
        foreach ($config as $k=>$v){
            if(in_array($data['class'],$v)){
                $class_num = $v['limitation'];
            }
        }
        $member_num = Db::name('user_member')
            ->where('class',$data['class'])
            ->count();
        if ($member_num>$class_num){
            return [
                'state' => 0,
                'errormsg' => '已是最高会员'
            ];
        }
        $data['user_id'] = $user_id;
        $data['admin_user_id'] = $this->userId;
        $data['create_time'] = $_SERVER['REQUEST_TIME'];
        $data['state'] = 1;
        $res = Db::name('user_member')->insertGetId();
        if (!$res){
            return [
                'state'=> 0,
                'errormsg' => 'insert error'
            ];
        }
        return [
            'state' => 1,
        ];
    }
    //累计消费生成会员
    public function addRechargeAccumulate($tel){
        if (!$this->auth){
            return [
                'state' => 0,
                'errormsg' => '权限错误'
            ];
        }
        if(!$tel){
            return [
                'state' => 0,
                'errormsg' => '请输入电话号码'
            ];
        }
        //根据tel找到用户id
        $user = model('user')->exist(['state'=>1,'tel'=>$tel]);
        if (!$user['state']){
            return [
                '未找到用户'
            ];
        }
        $user_id = $user['data']['user_id'];
        //获取消费记录
        $prefix = config('database.prefix');
        $pay_info = Db::table($prefix.'pay')
            ->alias('a')
            ->join($prefix.'order b','a.order_id = b.order_id')
            ->where('b.user_id',$user_id)
            ->select();
        //获取配置文件
        $total_fee = 0;
        $class = [];
        if (!empty($pay_info)){
            foreach ($pay_info as $k=>$v){
                $total_fee += $v['total_fee'];
            }
        }
        $config = $this->config[0];
        foreach ($config as $key => $value){
            if ($total_fee>=$value['request']['recharge']){
                $class[] = $key;
            }
            $class_max[] = $key;
        }
        $class_max_select = implode(',',$class_max);
        //判断是否达到最低会员要求
        if (empty($class)){
            return [
                'state'=> 0,
                'errormsg' => '您暂不是会员'
            ];
        }
        //查询该用户所有会员卡
        $member = Db::name('user_member')
            ->where("user_id = $user_id and class in($class_max_select) and state=1")
            ->order('class desc')
            ->select();
        if (!$member){
            $data['class'] = $class[0];
        }else{
            foreach ($member as $k => $v) {
                if (!(time() - $v['create_time']) / 86400 > $v['temporality'] || !$v['temporality']) {
                    $user_info[] = $v;
                }
            }
            //如果可生成的会员卡类型高于已有会员卡类型，则提示生成对应梯度会员卡
            if ($class[0]>$member[0]['class']){
                $data['class'] = $class[0];
            }else{
                if($class_max[0]=$member[0]['class']){
                    return [
                        'state'=> 0,
                        'errormsg' => '会员卡升级'
                    ];
                }
                return [
                    'state' => 0,
                    'errormsg' => $member[0]['class']+1
                ];
            }
        }
        //会员卡数量限制
        $class_num = $config[$data['class']]['limitation'];
        $member_num = Db::name('user_member')
            ->where('class',$data['class'])
            ->count();
        if ($member_num>$class_num){
            return [
                'state' => 0,
                'errormsg' => '最高会员'
            ];
        }
        $data['user_id'] = $user_id;
        $data['admin_user_id'] = $this->userId;
        $data['create_time'] = $_SERVER['REQUEST_TIME'];
        $data['state'] = 1;
        $res = Db::name('user_member')->insertGetId();
        if (!$res){
            return [
                'state'=> 0,
                'errormsg' => '添加失败'
            ];
        }
        return [
            'state' => 1,
        ];
    }
    //获取用户可添加为的会员类型
    public function create_check($user_id){
        if (!$user_id){
            return [
                'state'=> 0,
                'errormsg' => '请输入用户id'
            ];
        }
        //通过接口获取user_id
        $user_info = model('User')->getInfoById($user_id);
       if (!$user_info){
           return [
               'state'=> 0,
               'errormsg' => '未找到用户'
           ];
       }
        //现在pay表里找到可以该用户可以生成的会员
        //再找到已有会员信息,若pay里的最大支付值可生成的会员在member表的该用户数据下已经生成过了，就返回不能再生成更高级别的会员了，如果没有或级别高于已生成的会员卡则直接生成pay表最大支付值对应级别会员。
        //获取消费记录
        $prefix = config('database.prefix');
        $pay_info = Db::table($prefix.'pay')
            ->alias('a')
            ->join($prefix.'order b','a.order_id = b.order_id')
            ->where('b.user_id',$user_id)
            ->where('b.class','0')
            ->order('b.create_time desc')
            ->select();
        //获取配置文件
        $total_fee = 0;
        $class = [];
        if (!empty($pay_info)){
            $total_fee = $pay_info[0]['total_fee'];
            $order_id = $pay_info[0]['order_id'];
        }
        $pay_refund = Db::name('pay_refund')->where('order_id',$order_id)->find();
        //取出会员卡配置
        $config = $this->config[0];
        foreach ($config as $key => $value){
            if ($total_fee>=$value['request']['recharge']){
                $class[] = $value['id'];
            }
            $class_max[] = $value['id'];
        }
        $class_max_select = implode(',',$class_max);
        //判断是否达到最低会员要求
        if (!isset($class[0])) {
            return [
                'state' => 0,
                'errormsg' => 'not qulified'
            ];
        }
        //会员卡数量限制
        $class_num='';
        foreach ($config as $k=>$v){
            if ($v['id']==$class[0]){
                $class_num = $v['limitation'];
                $demand = $k;
            }
        }
        $member_num = Db::name('user_member')
            ->where('class',$class[0])
            ->count();
        $data['user_id'] = $user_id;
        $data['admin_user_id'] = $this->userId;
        $data['create_time'] = $_SERVER['REQUEST_TIME'];
        $data['state'] = 1;
        $data['class'] = $class[0];
        //查询该用户所有会员卡
        $member = Db::name('user_member')
            ->where("user_id = $user_id and class in($class_max_select) and state=1")
            ->order('class desc')
            ->select();
        if (!$member){
                if ($member_num>$class_num){
                    return [
                        'state' => 0,
                        'errormsg' => 'limitation max'
                    ];
                }else{
                    $res = Db::name('user_member')->insertGetId($data);
                    return [
                        'state' => 1,
                        'data'=> $class[0]
                    ];
                }
        }else{
            foreach ($member as $k => $v) {
                if (!(time() - $v['create_time']) / 86400 > $v['temporality'] || !$v['temporality']) {
                    $user_info[] = $v;
                }
            }
            //如果可生成的会员卡类型高于已有会员卡类型，则提示生成对应梯度会员卡
            if (isset($class[0])&&$class[0]>$member[0]['class']){
                if ($member_num>$class_num){
                    return [
                        'state' => 0,
                        'errormsg' => 'limitation max'
                    ];
                }else{
                    $res = Db::name('user_member')->insertGetId($data);
                    return [
                        'state' => 1,
                        'data'=> $class[0]
                    ];
                }
            } else {
                if ($member[0]['class'] == $class_max[0]) {
                    return [
                        'state' => 0,
                        'data' => ''
                    ];
                }
                //下阶段会员卡
              return [
                    'state' => 0,
                    'data' =>''
                ];
            }
        }
    }
    //获取会员信息
    public function userList($field){
//        if (!$this->auth){
//            return [
//                'state' => 0,
//                'errormsg' => 'authority incorrect'
//            ];
//        }
        if (!$field){
            return [
                'state' => 0,
                'errormsg' => 'field error'
            ];
        }
        if (isset($field['page'])&&$field['page'] != '') {
            $pages = $field['page'] - 1;
        } else {
            $pages = 0;
        }
        if (isset($field['maxPerPage'])&&$field['maxPerPage'] != '') {
            $maxPerPage = $field['maxPerPage'];
        } else {
            $maxPerPage = 5;
        }
        $where = "admin_user_id !='' OR EXISTS(SELECT * FROM ".$this->prefix."user_tel WHERE user_id=".$this->prefix."user.user_id AND state=1) OR EXISTS(SELECT * FROM ".$this->prefix."user_card WHERE user_id=".$this->prefix."user.user_id AND state=1)";
        /*if(preg_match("/^1[34578]\d{9}$/", $field['keywords'])){
            $where = "EXISTS(SELECT * FROM ".$this->prefix."user_tel WHERE user_id=".$this->prefix."user.user_id AND state=1 AND tel=$field[keywords])";
        }elseif(is_numeric($field['keywords']) && (strlen($field['keywords'])>=8 && strlen($field['keywords'])<=20)){
            $where = "EXISTS(SELECT * FROM ".$this->prefix."user_card WHERE user_id=".$this->prefix."user.user_id AND state=1 AND card_code=$field[keywords])";
        }elseif($field['keywords']!=''){
            $where = keywordSQL($field['keywords'],'nickname,real_name,set_name');
        }*/
        if(isset($field['keywords'])&& $field['keywords']!=""){
            $user = model('user')->exist(['tel'=>$field['keywords']]);
            if($user['state']){
                $where = "user_id=".$user['data']['user_id'];
            }else{
                $card = model('card')->getUserIdByCode($field['keywords']);
                if($card['state']){
                    $where = "user_id=".$card['data']['user_id'];
                }else{
                    $where = keywordSQL($field['keywords'],'nickname,real_name,set_name');
                }
            }
        }
        $user = Db::name('user')
            ->where($where)
            ->limit($pages*$maxPerPage,$maxPerPage)
            ->order('join_time desc')
            ->select();
        //基本信息
        $member = [];
        $config = getConfig('member')[0];
        if (!empty($user)){
            foreach ($user as $k=>$v){
                $userinfo = model('User')->getInfoById($v['user_id']);
                $tel =  db('user_tel')->where("user_id = $v[user_id] and state=1")->find();
                if ($userinfo){
                    $member[$k]['user_name'] = $userinfo['set_name'] ? $userinfo['set_name']:$userinfo['user_name'];
                    $member[$k]['tel'] = isset($tel['tel']) ? $tel['tel']:'';
                    $member[$k]['headimgurl'] = isset($userinfo['headimgurl']) ? $userinfo['headimgurl'] : '';
                    $member[$k]['user_id'] = $userinfo['user_id'];
                    $member[$k]['join_time'] = $userinfo['join_time'];
                    if($v['admin_user_id']){
                        $admininfo = model('User')->getInfoById($v['admin_user_id']);
                        $member[$k]['admin_user_name'] = $admininfo['set_name'] ? $admininfo['set_name']:$admininfo['user_name'];
                    }else{
                        $member[$k]['admin_user_name'] = '';
                    }
                    $member[$k]['balance'] = model('Account')->getBalanceByUserId($v['user_id'])['data']['balance'];
                    $prefix = config('database.prefix');
                    $card_info = Db::table($prefix.'user')
                        ->alias('a')
                        ->join($prefix.'user_member b','a.user_id=b.user_id')
                        ->where('a.user_id',$v['user_id'])
                        ->where('b.state = 1')
                        ->order('b.class asc')
                        ->select();
                    foreach ($card_info as $kk =>$vv){
                        foreach ($config as $kkk => $vvv){
                            if($vv['class'] == $vvv['id']){
                                $date[$vvv['group']]=$vvv['id'];
                            }
                        }
                    }
                    if (!empty($card_info)){
                        foreach ($card_info as $k_k=>$v_v){
                            if(in_array($v_v['class'],$date)){
                                foreach ($config as $conf=>$vig){
                                    if($v_v['class'] == $vig['id']){
                                        $member[$k]['members'][$k_k]['discount'] = $vig['discount'];
                                        $member[$k]['members'][$k_k]['member_intro'] = $vig['intro'];
                                        $member[$k]['members'][$k_k]['demand'] = $conf;
                                        $member[$k]['members'][$k_k]['user_member_id'] = $v_v['user_member_id'];
                                        $member[$k]['members'][$k_k]['create_date'] = timeString($v_v['create_time']);
                                        $member[$k]['members'][$k_k]['class'] = $v_v['class'];
                                        $member[$k]['members'][$k_k]['temporality'] = $v_v['temporality'];
                                    }
                                }
                            }
                        }
                    }
                    //会员卡cards列表
                    $cards = Db::name('user_card')->where("state = '1' and user_id =".$v['user_id'])->select();
                    if (!empty($cards)){
                        $member[$k]['cards'] = $cards;
                        foreach ($cards as $key => $val) {
                            $member[$k]['cards'][$key]['card_code'] = substr_replace($val['card_code'], '****', 2, strlen($val['card_code']) - 6);
                        }
                    }
                }
            }
            foreach ($member as $key=>$item){
                if($item['admin_user_name']==""&& $item['tel']==""){
                    unset($member[$key]);
                }
            }
        }
        if(!$member){
            return [
                'state' =>0,
                'errormsg' => 'user not find'
            ];
        }
        $pages = $pages+1;
        $user_type = Db::name('user')
            ->where($where)
            ->limit($pages*$maxPerPage,$maxPerPage)->select();
        if (count($user_type)){
            $more = 1;
        }else{
            $more = 0;
        }
        return [
            'state'=> 1,
            'data'=>['list'=>$member,'more'=>$more,'maxPerPage'=>$maxPerPage]
        ];
    }
    //今日统计
    public function statisticsToday(){

        if (!$this->auth){
            return [
                'state' => 0,
                'errormsg' => 'authority incorrect'
            ];
        }
        //当前时间区间
        $begin_time = mktime(0,0,0,date('m'),date('d'),date('Y'));
        $end_time = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        //今日新增会员
        $data['member_amount_today'] = Db::name('user_member')
            ->where('state','1')
            ->where('create_time','EGT',$begin_time)
            ->where('create_time','ELT',$end_time)
            ->count();
        //昨日起始时间
        $yesterday_begin_time = mktime(0,0,0,date('m'),date('d')-1,date('Y'));
        $yesterday_end_time = mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
        //昨日新增会员
        $data['member_amount_yesterday'] = Db::name('user_member')
            ->where('state','1')
            ->where('create_time','EGT', $yesterday_begin_time)
            ->where('create_time','ELT',$yesterday_end_time)
            ->count();

        //会员累计总数
        $member_total = Db::name('user_member')
            ->where('state','1')
            ->select();
        if(!empty($member_total)){
            foreach ($member_total as $k => $v) {
                $member_total_user[$v['user_id']][] = $v;
            }
            $data['member_amount_all'] = count($member_total_user);
        }
        //今日会员充值记录
        $recharge = model('Account')->getRrecordListForAdmin('', 'statisics','','')['data']['list'];
        $recharge_a = 0;//充值总金额
        $refund = 0;//退款总金额
        $cashpay = 0;//现金收款
        $refund_cash = 0;//现金退款
        $alipay = 0;//支付宝收款
        $refund_alipay = 0;//支付宝退款
        $wxpay = 0;//微信支付收款
        $refund_wxpay = 0; //微信支付退款
        $accountpay = 0;//刷卡支付
        $refund_accountpay = 0;//刷卡退款
        if(!empty($recharge)){
            foreach ($recharge as $k=>$v){
                $recharge_a += $v['total_fee'];
                $refund += $v['refund_fee'];
                if(isset($v['cashpay'])&&$v['cashpay']==1){
                    $cashpay  += $v['total_fee'];
                    $refund_cash += $v['refund_fee'];
                }
                if (isset($v['alipay'])&&$v['alipay']==1){
                    $alipay  += $v['total_fee'];
                    $refund_alipay += $v['refund_fee'];
                }
                if (isset($v['wxpay'])&&$v['wxpay']==1){
                    $wxpay  += $v['total_fee'];
                    $refund_wxpay += $v['refund_fee'];
                }
                if (isset($v['accountpay'])&&$v['accountpay']==1){
                    $accountpay  += $v['total_fee'];
                    $refund_accountpay += $v['refund_fee'];
                }
            }
        }
        //总收入
        $data['total_fee'] = $recharge_a;
        $data['cash_total_fee'] = $cashpay;
        $data['alipay_total_fee'] = $alipay;
        $data['tenpay_total_fee'] = $wxpay;
        $data['accountpay_total_fee'] = $accountpay;
        //退款
        $data['refund_fee'] = $refund;
        $data['cash_refund_fee'] = $refund_cash;
        $data['alipay_refund_fee'] = $refund_alipay;
        $data['tenpay_refund_fee'] = $refund_wxpay;
        $data['accountpay_refund_fee'] = $refund_accountpay;
        //实际收入
        $data['reality_recharge'] = $recharge_a - $refund;
        $data['reaity_cash'] = $cashpay - $refund_cash;
        $data['reaity_alipay'] = $alipay - $refund_alipay;
        $data['reaity_wxpay'] = $wxpay - $refund_wxpay;
        $data['reaity_accountpay'] = $accountpay - $refund_accountpay;
        return [
            'state' => 1,
            'data' => ['info'=>$data]
        ];
    }
    //获取会员信息
    public function memberList($field){
        if (!$this->auth){
            return [
                'state' => 0,
                'errormsg' => 'authority incorrect'
            ];
        }
        if (!$field){
            return [
                'state' => 0,
                'errormsg' => 'field error'
            ];
        }
        if (isset($field['page'])&&$field['page'] != '') {
            $pages = $field['page'] - 1;
        } else {
            $pages = 0;
        }
        if (isset($field['maxPerPage'])&&$field['maxPerPage'] != '') {
            $maxPerPage = $field['maxPerPage'];
        } else {
            $maxPerPage = 12;
        }
        //当前时间区间
        //$begin_time = mktime(0,0,0,date('m'),date('d'),date('Y'));
       // $end_time = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        $where = "state=1 and EXISTS(SELECT * FROM ".$this->prefix."user_tel WHERE user_id=".$this->prefix."user_member.user_id AND state=1) 
                OR EXISTS(SELECT * FROM ".$this->prefix."user_card WHERE user_id=".$this->prefix."user_member.user_id AND state=1)
                OR EXISTS(SELECT * FROM ".$this->prefix."user WHERE user_id=".$this->prefix."user_member.user_id)";
        if(preg_match("/^1[34578]\d{9}$/", $field['keywords'])){
            $where = "state=1 AND EXISTS(SELECT * FROM ".$this->prefix."user_tel WHERE user_id=".$this->prefix."user_member.user_id AND state=1 AND tel=$field[keywords])";
        }elseif(is_numeric($field['keywords']) && (strlen($field['keywords'])>=8 && strlen($field['keywords'])<=20)){
            $where = "state=1 AND EXISTS(SELECT * FROM ".$this->prefix."user_card WHERE user_id=".$this->prefix."user_member.user_id AND state=1 AND card_code=$field[keywords])";
        }elseif($field['keywords']!=''){
            $where = keywordSQL($field['keywords'],"nickname,real_name,set_name");
            $where = "state=1 AND EXISTS(SELECT * FROM ".$this->prefix."user WHERE user_id=".$this->prefix."user_member.user_id AND state=1 AND $where)";
        }
        $user = Db::name('user_member')
            ->where($where)
            ->field("create_time,user_admin_id,class,user_id")
            ->order('create_time desc')
            ->limit($pages*$maxPerPage,$maxPerPage)
            ->select();
        //基本信息
        $member = [];
        $config = getConfig('member')[0];
        if (!empty($user)){
            foreach ($user as $k=>$v){
                $userinfo = model('User')->getInfoById($v['user_admin_id']);//Db::name('User')->where('user_id',$v['user_admin_id'])->find();
                $member[$k]['create_time'] = $v['create_time'];
                foreach ($config as $value=>$item){
                    if($item['id']==$v['class']){
                        $member[$k]['member_available'] = $item['intro'];
                    }
                }
                $member[$k]['admin_user_name'] = $userinfo['set_name'] ? $userinfo['set_name'] : $userinfo['user_name'];
                $user_admin = model('User')->getInfoById($v['user_id']);
                $member[$k]['user_id'] = $user_admin['user_id'];
                $member[$k]['user_name'] = $user_admin['set_name'] ? $user_admin['set_name']:$user_admin['user_name'];
                $member[$k]['tel'] = isset($user_admin['tel']) ? $user_admin['tel'] : "";
                $member[$k]['user_headimgurl'] = $user_admin['headimgurl'];
            }
        }
        if(!$member){
            return [
                'state' => 0,
                'errormsg' => 'members  not find'
            ];
        }
        //dump($member);
        $pages = $pages+1;
        $user_type = Db::name('user_member')
            ->where($where)
            ->field("create_time,user_admin_id,class,user_id")
            ->order('create_time desc')
            ->limit($pages*$maxPerPage,$maxPerPage)
            ->select();
        if (count($user_type)){
            $more = 1;
        }else{
            $more = 0;
        }
        return [
            'state'=> 1,
            'data'=>['list'=>$member,'more'=>$more,'maxPerPage'=>$maxPerPage]
        ];
    }
    //会员统计
    public function statisticsMemberNum($data)
    {
        //会员列表
        $data = ['start_time'=> '2016-12-01','end_time'=> '2017-05-12'];
        $startime = strtotime($data['start_time']);
        $endtime = strtotime($data['end_time']);
        if ($startime == $endtime) {
            $endtime = $startime + 86400;
        } else {
            $endtime = $endtime + 86399;
        }
        $member_total = Db::name('user_member')
            ->where('state','1')
            ->where("create_time >= $startime and create_time <= $endtime")
            ->select();
        if(!empty($member_total)) {
            foreach ($member_total as $k => $v) {
                $member_total_user[date("Y-m",$v['create_time'])][] = $v;
            }
        }
        foreach ($member_total_user as $key=>$value){
           foreach ($value as $k=>$v){
              $member_user[$key][$v['user_id']][] = $v;
           }
        }
        $config = getConfig('member')[0];
        foreach ($member_user as $key=>$value){
            $member[$key]['ammount'] = count($value);
            foreach ($value as $k=>$v){
                array_multisort(array_column($v, 'class'), SORT_DESC, $v);
                $member[$key]['class'][] = $v[0]['class'];
            }
        }
        foreach ($member as $key=>$value){
            foreach ($config as $k=>$v){
                $member[$key][$k] = 0;
                foreach ($value['class'] as $c=>$r){
                    if($r==$v['id']){
                        $member[$key][$k] += 1;
                    }
                }
            }
            /*foreach ($member_user[$key] as $k=>$v){
                $member[$key]['user'][] = model('user')->getInfoById($k);
            }*/
            unset($member[$key]['class']);
        }
        return ['state'=>1,'data'=>['list'=>$member]];
    }
}
